package com.mz361.stdapi.controller;

import com.alibaba.fastjson.JSONObject;
import com.mz361.common.utils.ResultVoUtil;
import com.mz361.common.utils.StringUtil;
import com.mz361.common.vo.ResultVo;
import com.mz361.component.jwt.annotation.IgnorePermissions;
import com.mz361.modules.system.domain.PayOrder;
import com.mz361.stdapi.domain.PayOrderResult;
import com.mz361.stdapi.service.PayOrderResultService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.security.GeneralSecurityException;

/**
 * @author niceale
 * @ date 2024/06/07
 */
@Api(tags = "支付调用接口")
@RestController
@Slf4j
public class PayOrderController {
    @Autowired
    PayOrderResultService payOrderResultService;

    @ApiOperation(value = "支付接口", notes = "支付接口Native支付返回支付二维码，用户手机扫描支付")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "key", dataType = "String", dataTypeClass = String.class, paramType = "Header", value = "渠道KEY", required = true),
            @ApiImplicitParam(name = "timestamp", dataType = "String", dataTypeClass = String.class, paramType = "Header", value = "时间戳", required = true),
            @ApiImplicitParam(name = "token", dataType = "String", dataTypeClass = String.class, paramType = "Header", value = "MD5(KEY+timestamp+密钥)", required = true),
            @ApiImplicitParam(name = "userId", dataType = "String", dataTypeClass = String.class, paramType = "Header", value = "用户ID", required = true),
            @ApiImplicitParam(name = "name", dataType = "String", dataTypeClass = String.class, paramType = "query", value = "套餐标识/标准号"),
            @ApiImplicitParam(name = "orderType", dataType = "String", dataTypeClass = String.class, paramType = "query", value = "订单类型：1：标准订单；2 : 套餐订单"),
            @ApiImplicitParam(name = "payType", dataType = "String", paramType = "query", value = "支付方式 0:微信Native支付 1:支付宝Navtive支付 2:微信H5支付 3:微信JSAPI支付 5:支付宝PC网页支付", defaultValue = "0", dataTypeClass = String.class),
            @ApiImplicitParam(name = "amunt", dataType = "String", dataTypeClass = String.class, paramType = "query", value = "金额（单位元）")
    })
    @GetMapping("/api/v1/payOrder")
    @CrossOrigin
    public ResultVo payOrder(@RequestHeader String userId, String name, String payType, String orderType, String amunt) {
        log.info("payOrder  userId = {}, name = {}, payType = {}, orderType = {}, amunt = {}", userId, name, payType, orderType, amunt);
        if (StringUtil.isEmpty(payType)) {
            payType = "0";
        }
        PayOrderResult payOrderResult = payOrderResultService.createPayOrder(userId, name, Integer.valueOf(amunt), payType, orderType);
        if (payOrderResult != null && StringUtil.notEmpty(payOrderResult.getCodeUrl())) {
            return ResultVoUtil.success("成功", payOrderResult);
        }
        return ResultVoUtil.error("支付失败");
    }


    @ApiOperation(value = "刷新二维码", notes = "支付接口Native支付返回支付二维码，用户手机扫描支付")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "key", dataType = "String", dataTypeClass = String.class, paramType = "Header", value = "渠道KEY", required = true),
            @ApiImplicitParam(name = "timestamp", dataType = "String", dataTypeClass = String.class, paramType = "Header", value = "时间戳", required = true),
            @ApiImplicitParam(name = "token", dataType = "String", dataTypeClass = String.class, paramType = "Header", value = "MD5(KEY+timestamp+密钥)", required = true),
            @ApiImplicitParam(name = "userId", dataType = "String", dataTypeClass = String.class, paramType = "Header", value = "用户ID", required = true),
            @ApiImplicitParam(name = "orderId", dataType = "String", dataTypeClass = String.class, paramType = "query", value = "订单号")
    })
    @GetMapping("/api/v1/refreshCodeUrl")
    @CrossOrigin
    public ResultVo refreshCodeUrl(@RequestHeader String userId, String orderId) {
        log.info("refreshCodeUrl  userId = {}, name = {}", userId, orderId);
        PayOrderResult payOrderResult = payOrderResultService.refreshPaymentCode(orderId);
        if (payOrderResult != null && StringUtil.notEmpty(payOrderResult.getCodeUrl())) {
            return ResultVoUtil.success("成功", payOrderResult);
        }
        return ResultVoUtil.error("刷新失败");
    }

    @ApiOperation(value = "支付状态查询", notes = "支付状态查询，用户点击支付完成调用此接口查询是否支付成功")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "key", dataType = "String", dataTypeClass = String.class, paramType = "Header", value = "渠道KEY", required = true),
            @ApiImplicitParam(name = "timestamp", dataType = "String", dataTypeClass = String.class, paramType = "Header", value = "时间戳", required = true),
            @ApiImplicitParam(name = "token", dataType = "String", dataTypeClass = String.class, paramType = "Header", value = "MD5(KEY+timestamp+密钥)", required = true),
            @ApiImplicitParam(name = "userId", dataType = "String", dataTypeClass = String.class, paramType = "Header", value = "用户ID", required = true),
            @ApiImplicitParam(name = "orderId", dataType = "String", dataTypeClass = String.class, paramType = "query", value = "订单号", required = true)
    })
    @GetMapping("/api/v1/getPayStatus")
    @CrossOrigin
    public ResultVo<PayOrderResult> getPayStatus(@RequestHeader String key, @RequestHeader String timestamp, @RequestHeader String token, @RequestHeader String userId, String orderId) {
        log.info("getPayStatus key = {}, timestamp = {}, token = {}, userId = {}, orderId = {}", key, timestamp, token, userId, orderId);
        PayOrderResult payOrderResult = payOrderResultService.queryPaymentStatus(orderId);
        return ResultVoUtil.success("成功", payOrderResult);
    }

    @ApiOperation(value = "微信支付回调接口", notes = "用户支付成功后，微信通过回调接口通知支付结果")
    @PostMapping("/api/v1/notify")
    @CrossOrigin
    @IgnorePermissions
    public void wxNotify(@RequestBody JSONObject jsonObject) throws GeneralSecurityException, IOException {
        log.info("notify jsonObject = {}", jsonObject.toJSONString());
        payOrderResultService.processWeChatPaymentNotification(jsonObject);

    }

    @ApiOperation(value = "支付宝支付回调接口", notes = "用户支付成功后，支付宝通过回调接口通知支付结果")
    @PostMapping("/api/v1/aliNotify")
    @CrossOrigin
    @IgnorePermissions
    public String aliNotify(HttpServletRequest request) throws Exception {
        log.info("aliNotify request = {}", JSONObject.toJSONString(request.getParameterMap()));
        PayOrder payOrder = payOrderResultService.processAlipayPaymentNotification(request);
        if (null != payOrder) {
            return "success";
        } else {
            return "fail";
        }
    }

}
